import json
from typing import Dict

from app.controllers.gaolu_controller import gaolu_auto_score
from app.controllers.luzha_controller import luzha_prediction
from app.controllers.response.response import SuccessResult
from app.database import convert
from app.models.po.integration.gaolu_integration import GaoLuIntegrationPO, GaoLuIntegrationOperation
from app.models.po.integration.hanfan_integration import HanFanIntegrationPO,HanfanIntegrationOperation
from app.models.po.integration.lugang_integration import LuGangIntegrationPO
from app.models.po.lugang.lugang_original_po import LuGangActivinessPredictPO
from datetime import datetime

from app.services.business import hanfan_biz_service, gaolu_biz_service
from app.utils import date_util, sys_utils
import logging as log

def dump():
    # hanfan_dict = _hanfan()
    # luzha_dict = _luzha()
    # gaolu_dict = _gaolu()
    # lugang_dict = _lugang()
    #
    # result = dict(hanfan=hanfan_dict,
    #               luzha=luzha_dict,
    #               gaolu=gaolu_dict,
    #        `       lugang=lugang_dict)
    log.info("开始含钒，炉渣，高炉，炉钢数据同步")
    _hanfan_and_luzha()
    _gaolu()
    _lugang()

    return dict(resp="ok")


def _hanfan_and_luzha():
    end_time = datetime.now()
    end_time = sys_utils.get_time_round_and_adjust(end_time, step=0, round_level='hour')
    start_time = sys_utils.get_time_round_and_adjust(end_time, step=-1, round_level='hour')
    hanfan_result_detail = hanfan_biz_service.auto_score(start_time, end_time)

    # hanfan_result_detail = hanfan_result['detail']

    curScore: Dict = hanfan_result_detail.get('curScore', {})
    lastHourScore: Dict = hanfan_result_detail.get('lastHourScore', {})

    hanfan_datetime = curScore.get('DateTime', "")
    cg_lt_gl_gl04_tie_v = curScore.get('CG_LT_GL_GL04_Score', 0)
    cg_lt_gl_gl04_tie_v_predict = curScore.get('CG_LT_GL_GL04_Score_predict', 0)

    cg_lt_gl_gl04_tie_v_last_hour = lastHourScore.get('CG_LT_GL_GL04_Score', 0)
    cg_lt_gl_gl04_tie_v_predict_last_hour = lastHourScore.get('CG_LT_GL_GL04_Score_predict', 0)

    best_value = hanfan_result_detail.get('bestValue', 0)
    shoude = hanfan_result_detail.get('shoude', 0)
    hanfan_recommend_list: list = hanfan_result_detail.get('recommend', [])

    #### 以下是luzha
    luzha_result = luzha_prediction()
    luzha_result_detail = json.loads(luzha_result.data.decode("utf8"))['detail']
    # luzha_result_detail = luzha_result['detail']

    main = luzha_result_detail.get('main', [{}, {}, {}])
    zha_r = main[0]
    zha_r_current = zha_r.get('current', 0)
    zha_r_predict = zha_r.get('predict', 0)

    mg_al = main[1]
    mg_al_current = mg_al.get('current', 0)
    mg_al_predict = mg_al.get('predict', 0)

    ti_o2 = main[2]
    ti_o2_current = ti_o2.get('current', 0)
    ti_o2_predict = ti_o2.get('predict', 0)
    luzha_recommend_list: list = luzha_result_detail.get('recommend', [])

    hanfan_integration = HanFanIntegrationPO()
    hanfan_integration.create_time = datetime.now()
    hanfan_integration.date_time = date_util.parse_date_time(hanfan_datetime)
    hanfan_integration.actual_v = cg_lt_gl_gl04_tie_v
    hanfan_integration.predict_v = cg_lt_gl_gl04_tie_v_predict
    hanfan_integration.actual_v_last_hour = cg_lt_gl_gl04_tie_v_last_hour
    hanfan_integration.predict_v_last_hour = cg_lt_gl_gl04_tie_v_predict_last_hour
    hanfan_integration.best_v = best_value
    hanfan_integration.shoude_v = shoude
    hanfan_integration.actual_r2 = zha_r_current
    hanfan_integration.predict_r2 = zha_r_predict
    hanfan_integration.actual_mg_al = mg_al_current
    hanfan_integration.predict_mg_al = mg_al_predict
    hanfan_integration.actual_tio2 = ti_o2_current
    hanfan_integration.predict_tio2 = ti_o2_predict

    convert.add_one(hanfan_integration)


    hanfan_operation_list = list()
    luzha_operation_list = list()
    for hanfan_recommend in hanfan_recommend_list:
        operation = HanfanIntegrationOperation()
        operation.key = hanfan_recommend['key']
        operation.type = 'luzha'
        operation.status = hanfan_recommend['status']
        operation.recommend = hanfan_recommend['recommend']
        operation.hanfan_integration_id = hanfan_integration.id
        hanfan_operation_list.append(operation)

    for hanfan_recommend in luzha_recommend_list:
        operation = HanfanIntegrationOperation()
        operation.key = hanfan_recommend['key']
        operation.type = 'hanfan'
        operation.status = hanfan_recommend['status']
        operation.recommend = hanfan_recommend['recommend']
        operation.hanfan_integration_id = hanfan_integration.id
        luzha_operation_list.append(operation)

    convert.add_all(hanfan_operation_list)
    convert.add_all(luzha_operation_list)



def _luzha():
    luzha_result = luzha_prediction()
    luzha_result_detail = json.loads(luzha_result.data.decode("utf8"))['detail']
    # luzha_result_detail = luzha_result['detail']

    main = luzha_result_detail['main']
    zha_r = main[0]
    zha_r_current = zha_r['current']
    zha_r_predict = zha_r['predict']

    mg_al = main[1]
    mg_al_current = mg_al['current']
    mg_al_predict = mg_al['predict']

    ti_o2 = main[2]
    ti_o2_current = ti_o2['current']
    ti_o2_predict = ti_o2['predict']
    luzha_recommend_list: list = luzha_result_detail['recommend']

    return dict(zha_r_current=zha_r_current, zha_r_predict=zha_r_predict,
                mg_al_current=mg_al_current, mg_al_predict=mg_al_predict,
                ti_o2_current=ti_o2_current, ti_o2_predict=ti_o2_predict,
                luzha_recommend_list=luzha_recommend_list)


def _gaolu():
    end_time = datetime.now()
    end_time = sys_utils.get_time_round_and_adjust(end_time, step=0, round_level='hour')
    start_time = sys_utils.get_time_round_and_adjust(end_time, step=-1, round_level='hour')
    gaolu_result_detail = gaolu_biz_service.auto_score(start_time, end_time)

    log.info(json.dumps(gaolu_result_detail,ensure_ascii=False))
    # gaolu_result_detail = gaolu_result['detail']
    cur_score = gaolu_result_detail.get('curScore', {})
    gaolu_datetime = cur_score.get('DateTime', "")


    if date_util.parse_date_time(gaolu_datetime) is None:
        return

    gaolu_datetime = cur_score.get('DateTime', "")
    cg_lt_gl_gl04_score = cur_score.get('CG_LT_GL_GL04_Score', 0)
    cg_lt_gl_gl04_status = cur_score.get('CG_LT_GL_GL04_Status', '正常')

    score_trend_desc = gaolu_result_detail.get('desc', '')
    status_warning = gaolu_result_detail.get('statusWarning', '')
    stage_warning = gaolu_result_detail.get('stageWarning', '')

    reason_scope = gaolu_result_detail.get('reasonScope', {})
    value_dict = gaolu_result_detail.get("valueDict",{})
    status = gaolu_result_detail.get('status', '')

    gaolu_integration = GaoLuIntegrationPO()

    gaolu_integration.create_time = datetime.now()
    gaolu_integration.date_time = date_util.parse_date_time(gaolu_datetime)
    gaolu_integration.score = cg_lt_gl_gl04_score
    gaolu_integration.score_evaluation = cg_lt_gl_gl04_status
    gaolu_integration.trend_warning = score_trend_desc
    gaolu_integration.status_warning = status_warning
    gaolu_integration.stage_warning = stage_warning

    convert.add_one(gaolu_integration)

    gaolu_integration_operation_list = list()
    for k,v in reason_scope.items():
        operation = GaoLuIntegrationOperation()
        key = k.replace("_status","")
        operation.key = key
        operation.name = value_dict.get(key,"")
        operation.scope = v
        operation.status =status.get(k,"")
        operation.gaolu_integration_id = gaolu_integration.id
        gaolu_integration_operation_list.append(operation)

    convert.add_all(gaolu_integration_operation_list)

    # return dict(gaolu_datetime=gaolu_datetime, cg_lt_gl_gl04_score=cg_lt_gl_gl04_score,
    #             cg_lt_gl_gl04_status=cg_lt_gl_gl04_status, score_trend_desc=score_trend_desc,
    #             status_warning=status_warning, reason_scope=reason_scope, status=status)


def _lugang():
    long: LuGangActivinessPredictPO = convert.query(LuGangActivinessPredictPO,
                                                    LuGangActivinessPredictPO.level == 'day',
                                                    LuGangActivinessPredictPO.type == 'longTerm',
                                                    order_by=LuGangActivinessPredictPO.id.desc()).first()

    long_current = long.current
    long_predict = long.predict

    short: LuGangActivinessPredictPO = convert.query(LuGangActivinessPredictPO,
                                                     LuGangActivinessPredictPO.level == 'hour',
                                                     LuGangActivinessPredictPO.type == 'short',
                                                     order_by=LuGangActivinessPredictPO.id.desc()).first()

    short_current = short.current
    short_predict = short.predict

    lugang_integration = LuGangIntegrationPO()
    lugang_integration.create_time = datetime.now()
    lugang_integration.date_time = datetime.now()
    lugang_integration.heart_actual_long = long_current
    lugang_integration.heart_predict_long = long_predict
    lugang_integration.heart_actual_short = short_current
    lugang_integration.heart_predict_short = short_predict

    convert.add_one(lugang_integration)

    # return dict(long_current=long_current,long_predict=long_predict,
    #             short_current=short_current,short_predict=short_predict)


if __name__ == "__main__":
    result = {}
    result['recommend'] = []
    result['recommend'].append(dict(key="但是", status="但是", recommend="佛挡杀佛递四方速递"))
    r = SuccessResult(detail=result)
    print(123)
